// 全局变量
let currentCategory = '';
let currentEditName = '';
let allNavigationData = {};
let currentTab = 'my';
let tabConfig = [
    { id: 'my', name: '我的导航', icon: 'fas fa-star' },
    { id: 'ai', name: 'AI工具', icon: 'fas fa-robot' },
    { id: 'shopping', name: '商城购物', icon: 'fas fa-shopping-cart' },
    { id: 'entertainment', name: '视频娱乐', icon: 'fas fa-play-circle' },
    { id: 'news', name: '新闻资讯', icon: 'fas fa-newspaper' }
];
let linkOrder = {}; // 存储每个分类的链接顺序

// 收藏夹数据结构
let favoritesData = {
    folders: [],
    favorites: []
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadFromLocalStorage();
    loadTabConfig();
    loadLinkOrder();
    loadFavoritesData();
    setupEventListeners();
    renderTabs();
    loadNavigationData();
});

// 设置事件监听器
function setupEventListeners() {
    // 搜索功能
    const searchInput = document.getElementById('searchInput');
    searchInput.addEventListener('input', function() {
        filterLinks(this.value);
    });

    // Tab切换功能
    const tabBtns = document.querySelectorAll('.tab-btn');
    tabBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const tabName = this.getAttribute('data-tab');
            switchTab(tabName);
        });
    });

    // 添加链接表单
    const addForm = document.getElementById('addForm');
    addForm.addEventListener('submit', function(e) {
        e.preventDefault();
        addNewLink();
    });

    // 编辑链接表单
    const editForm = document.getElementById('editForm');
    editForm.addEventListener('submit', function(e) {
        e.preventDefault();
        updateLink();
    });

    // 添加Tab表单
    const addTabForm = document.getElementById('addTabForm');
    addTabForm.addEventListener('submit', function(e) {
        e.preventDefault();
        addNewTab();
    });

    // 添加文件夹表单
    const addFolderForm = document.getElementById('addFolderForm');
    addFolderForm.addEventListener('submit', function(e) {
        e.preventDefault();
        addNewFolder();
    });

    // 添加收藏表单
    const addFavoriteForm = document.getElementById('addFavoriteForm');
    addFavoriteForm.addEventListener('submit', function(e) {
        e.preventDefault();
        addNewFavorite();
    });

    // 模态框关闭事件
    const modals = document.querySelectorAll('.modal');
    modals.forEach(modal => {
        const closeBtn = modal.querySelector('.close');
        closeBtn.addEventListener('click', function() {
            modal.style.display = 'none';
        });

        // 点击模态框外部关闭
        modal.addEventListener('click', function(e) {
            if (e.target === modal) {
                modal.style.display = 'none';
            }
        });
    });
}

// Tab管理功能
function loadTabConfig() {
    const savedConfig = localStorage.getItem('tabConfig');
    if (savedConfig) {
        tabConfig = JSON.parse(savedConfig);
    }
}

function saveTabConfig() {
    localStorage.setItem('tabConfig', JSON.stringify(tabConfig));
}

function renderTabs() {
    // 渲染tab按钮
    const tabButtons = document.getElementById('tab-buttons');
    tabButtons.innerHTML = '';
    
    tabConfig.forEach((tab, index) => {
        const tabBtn = document.createElement('button');
        tabBtn.className = `tab-btn ${index === 0 ? 'active' : ''}`;
        tabBtn.setAttribute('data-tab', tab.id);
        tabBtn.innerHTML = `
            <i class="${tab.icon}"></i> <span class="tab-name-text">${tab.name}</span>
            <button class="tab-edit-btn" onclick="editTab('${tab.id}')" title="编辑">
                <i class="fas fa-edit"></i>
            </button>
            <button class="tab-delete-btn" onclick="deleteTab('${tab.id}')" title="删除">
                <i class="fas fa-trash"></i>
            </button>
        `;
        tabBtn.addEventListener('click', function() {
            switchTab(tab.id);
        });
        tabButtons.appendChild(tabBtn);
    });
    
    // 渲染tab内容
    const tabContent = document.getElementById('tab-content');
    tabContent.innerHTML = '';
    
    tabConfig.forEach((tab, index) => {
        const tabPane = document.createElement('div');
        tabPane.className = `tab-pane ${index === 0 ? 'active' : ''}`;
        tabPane.id = `${tab.id}-tab`;
        
        tabPane.innerHTML = `
            <div class="tab-header-actions">
                <button class="add-btn" onclick="showAddModal('${tab.id}')">
                    <i class="fas fa-plus"></i> 添加链接
                </button>
            </div>
            <div class="links-grid" id="${tab.id}-links"></div>
        `;
        
        tabContent.appendChild(tabPane);
    });
}

// Tab切换功能
function switchTab(tabName) {
    // 更新当前tab
    currentTab = tabName;
    
    // 更新tab按钮状态
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');
    
    // 更新tab内容显示
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.remove('active');
    });
    document.getElementById(`${tabName}-tab`).classList.add('active');
    
    // 渲染当前tab的数据
    renderCategory(tabName, allNavigationData[tabName] || {});
}

// 本地存储功能
function saveToLocalStorage() {
    try {
        localStorage.setItem('navigationData', JSON.stringify(allNavigationData));
        localStorage.setItem('linkOrder', JSON.stringify(linkOrder));
        localStorage.setItem('favoritesData', JSON.stringify(favoritesData));
        localStorage.setItem('lastSync', Date.now());
    } catch (error) {
        console.error('保存到本地存储失败:', error);
    }
}

function loadFromLocalStorage() {
    try {
        const savedData = localStorage.getItem('navigationData');
        if (savedData) {
            allNavigationData = JSON.parse(savedData);
            renderAllCategories();
        }
    } catch (error) {
        console.error('从本地存储加载失败:', error);
    }
}

function loadLinkOrder() {
    try {
        const savedOrder = localStorage.getItem('linkOrder');
        if (savedOrder) {
            linkOrder = JSON.parse(savedOrder);
        }
    } catch (error) {
        console.error('加载链接顺序失败:', error);
    }
}

// 加载收藏夹数据
function loadFavoritesData() {
    try {
        const savedFavorites = localStorage.getItem('favoritesData');
        if (savedFavorites) {
            favoritesData = JSON.parse(savedFavorites);
        }
    } catch (error) {
        console.error('加载收藏夹数据失败:', error);
    }
}

// 加载导航数据
async function loadNavigationData() {
    try {
        const response = await fetch('/api/navigation');
        if (response.ok) {
            const serverData = await response.json();
            
            // 合并服务器数据和本地数据
            Object.keys(serverData).forEach(category => {
                if (!allNavigationData[category]) {
                    allNavigationData[category] = {};
                }
                Object.assign(allNavigationData[category], serverData[category]);
            });
            
            renderAllCategories();
            saveToLocalStorage();
        } else {
            console.error('加载数据失败');
        }
    } catch (error) {
        console.error('网络错误:', error);
        // 如果网络错误，使用本地数据
        if (Object.keys(allNavigationData).length > 0) {
            renderAllCategories();
        }
    }
}

// Tab增删改功能
function showAddTabModal() {
    document.getElementById('addTabModal').style.display = 'block';
    document.getElementById('tabName').focus();
}

function closeAddTabModal() {
    document.getElementById('addTabModal').style.display = 'none';
    document.getElementById('addTabForm').reset();
}

function addNewTab() {
    const name = document.getElementById('tabName').value.trim();
    const icon = document.getElementById('tabIcon').value;
    
    if (!name) {
        alert('请输入Tab名称');
        return;
    }
    
    // 生成唯一ID
    const id = 'tab_' + Date.now();
    
    // 添加到配置
    tabConfig.push({ id, name, icon });
    saveTabConfig();
    
    // 重新渲染
    renderTabs();
    closeAddTabModal();
    showSuccessMessage('Tab添加成功！');
}

function editTab(tabId) {
    const tab = tabConfig.find(t => t.id === tabId);
    if (!tab) return;
    
    // 找到对应的tab按钮
    const tabBtn = document.querySelector(`[data-tab="${tabId}"]`);
    if (!tabBtn) return;
    
    // 获取tab名称的文本节点
    const tabNameText = tabBtn.querySelector('.tab-name-text');
    if (!tabNameText) return;
    
    // 创建输入框
    const input = document.createElement('input');
    input.type = 'text';
    input.value = tab.name;
    input.className = 'tab-name-edit-input';
    input.style.cssText = `
        background: transparent;
        border: 2px solid #667eea;
        border-radius: 4px;
        padding: 2px 6px;
        font-size: inherit;
        font-family: inherit;
        color: inherit;
        width: 120px;
        outline: none;
    `;
    
    // 替换文本为输入框
    const originalText = tabNameText.textContent;
    tabNameText.style.display = 'none';
    tabNameText.parentNode.insertBefore(input, tabNameText);
    
    // 聚焦输入框
    input.focus();
    input.select();
    
    // 处理保存
    function saveTabName() {
        const newName = input.value.trim();
        if (newName && newName !== originalText) {
            tab.name = newName;
            saveTabConfig();
            renderTabs();
            showSuccessMessage('Tab更新成功！');
        } else {
            // 恢复原文本
            tabNameText.style.display = 'inline';
            input.remove();
        }
    }
    
    // 处理取消
    function cancelEdit() {
        tabNameText.style.display = 'inline';
        input.remove();
    }
    
    // 绑定事件
    input.addEventListener('blur', saveTabName);
    input.addEventListener('keydown', function(e) {
        if (e.key === 'Enter') {
            saveTabName();
        } else if (e.key === 'Escape') {
            cancelEdit();
        }
    });
}

function deleteTab(tabId) {
    if (tabConfig.length <= 1) {
        alert('至少需要保留一个Tab');
        return;
    }
    
    if (!confirm('确定要删除这个Tab吗？删除后其中的链接将无法恢复。')) {
        return;
    }
    
    // 删除tab配置
    tabConfig = tabConfig.filter(t => t.id !== tabId);
    saveTabConfig();
    
    // 删除相关数据
    delete allNavigationData[tabId];
    saveToLocalStorage();
    
    // 重新渲染
    renderTabs();
    showSuccessMessage('Tab删除成功！');
}

// 全局同步功能
async function syncAllToServer() {
    const syncBtn = document.querySelector('.global-sync-up-btn');
    syncBtn.classList.add('syncing');
    
    try {
        // 保存所有本地数据到服务器
        for (const category of Object.keys(allNavigationData)) {
            const localLinks = allNavigationData[category] || {};
            for (const [name, url] of Object.entries(localLinks)) {
                await fetch(`/api/navigation/${category}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ name, url })
                });
            }
        }
        
        showSuccessMessage('所有数据上传到服务器成功！');
    } catch (error) {
        console.error('上传失败:', error);
        showSuccessMessage('上传失败，请检查网络连接');
    } finally {
        syncBtn.classList.remove('syncing');
    }
}

async function syncAllFromServer() {
    const syncBtn = document.querySelector('.global-sync-down-btn');
    syncBtn.classList.add('syncing');
    
    try {
        // 从服务器获取最新数据
        const response = await fetch('/api/navigation');
        if (response.ok) {
            const serverData = await response.json();
            
            // 更新所有分类的数据
            allNavigationData = serverData;
            saveToLocalStorage();
            renderAllCategories();
            showSuccessMessage('从服务器下载所有数据成功！');
        }
    } catch (error) {
        console.error('下载失败:', error);
        showSuccessMessage('下载失败，请检查网络连接');
    } finally {
        syncBtn.classList.remove('syncing');
    }
}

// 渲染所有分类
function renderAllCategories() {
    const categories = ['my', 'ai', 'shopping', 'entertainment', 'news'];
    categories.forEach(category => {
        renderCategory(category, allNavigationData[category] || {});
    });
}

// 渲染单个分类
function renderCategory(category, links) {
    const container = document.getElementById(`${category}-links`);
    if (!container) return;

    container.innerHTML = '';
    
    if (Object.keys(links).length === 0) {
        container.innerHTML = '<p style="color: #999; text-align: center; padding: 20px;">暂无链接，点击添加按钮开始添加</p>';
        return;
    }

    // 获取排序后的链接列表
    const sortedLinks = getSortedLinks(category, links);
    
    sortedLinks.forEach(([name, url]) => {
        const linkItem = createLinkItem(name, url, category);
        container.appendChild(linkItem);
    });
    
    // 初始化拖拽排序
    initDragAndDrop(container, category);
}

// 获取排序后的链接
function getSortedLinks(category, links) {
    if (!linkOrder[category] || linkOrder[category].length === 0) {
        // 如果没有保存的顺序，按字母顺序排序
        return Object.entries(links).sort(([a], [b]) => a.localeCompare(b));
    }
    
    // 按保存的顺序排序
    const orderedLinks = [];
    const linkMap = new Map(Object.entries(links));
    
    // 先添加有序的链接
    linkOrder[category].forEach(name => {
        if (linkMap.has(name)) {
            orderedLinks.push([name, linkMap.get(name)]);
            linkMap.delete(name);
        }
    });
    
    // 添加新增的链接（按字母顺序）
    const remainingLinks = Array.from(linkMap.entries()).sort(([a], [b]) => a.localeCompare(b));
    orderedLinks.push(...remainingLinks);
    
    return orderedLinks;
}

// 创建链接项
function createLinkItem(name, url, category) {
    const linkItem = document.createElement('div');
    linkItem.className = 'link-item';
    linkItem.setAttribute('data-name', name);
    linkItem.setAttribute('data-category', category);

    linkItem.innerHTML = `
        <a href="${url}" target="_blank" title="${url}">${name}</a>
        <div class="link-actions">
            <button class="action-btn edit-btn" onclick="showEditModal('${category}', '${name}', '${url}')" title="编辑">
                <i class="fas fa-edit"></i>
            </button>
            <button class="action-btn delete-btn" onclick="deleteLink('${category}', '${name}')" title="删除">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `;

    return linkItem;
}

// 拖拽排序功能
function initDragAndDrop(container, category) {
    const items = container.querySelectorAll('.link-item');
    
    items.forEach((item, index) => {
        item.setAttribute('draggable', true);
        item.setAttribute('data-index', index);
        
        // 拖拽开始
        item.addEventListener('dragstart', function(e) {
            e.dataTransfer.effectAllowed = 'move';
            e.dataTransfer.setData('text/html', this.outerHTML);
            this.classList.add('dragging');
        });
        
        // 拖拽结束
        item.addEventListener('dragend', function(e) {
            this.classList.remove('dragging');
        });
        
        // 拖拽经过
        item.addEventListener('dragover', function(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
        });
        
        // 拖拽进入
        item.addEventListener('dragenter', function(e) {
            e.preventDefault();
            this.classList.add('drag-over');
        });
        
        // 拖拽离开
        item.addEventListener('dragleave', function(e) {
            this.classList.remove('drag-over');
        });
        
        // 放置
        item.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('drag-over');
            
            const draggedItem = container.querySelector('.dragging');
            if (draggedItem && draggedItem !== this) {
                const draggedIndex = parseInt(draggedItem.getAttribute('data-index'));
                const dropIndex = parseInt(this.getAttribute('data-index'));
                
                // 重新排序
                reorderLinks(category, draggedIndex, dropIndex);
            }
        });
    });
}

// 重新排序链接
function reorderLinks(category, fromIndex, toIndex) {
    const links = allNavigationData[category] || {};
    const linkNames = Object.keys(links);
    
    if (!linkOrder[category]) {
        linkOrder[category] = linkNames;
    }
    
    // 获取拖拽的链接名称
    const draggedName = linkOrder[category][fromIndex];
    
    // 从原位置移除
    linkOrder[category].splice(fromIndex, 1);
    
    // 插入到新位置
    linkOrder[category].splice(toIndex, 0, draggedName);
    
    // 保存顺序
    saveToLocalStorage();
    
    // 重新渲染
    renderCategory(category, links);
    
    showSuccessMessage('链接顺序已更新！');
}

// 显示添加模态框
function showAddModal(category) {
    currentCategory = category;
    document.getElementById('addModal').style.display = 'block';
    document.getElementById('linkName').focus();
}

// 关闭添加模态框
function closeModal() {
    document.getElementById('addModal').style.display = 'none';
    document.getElementById('addForm').reset();
}

// 显示编辑模态框
function showEditModal(category, name, url) {
    currentCategory = category;
    currentEditName = name;
    
    document.getElementById('editLinkName').value = name;
    document.getElementById('editLinkUrl').value = url;
    document.getElementById('editModal').style.display = 'block';
    document.getElementById('editLinkName').focus();
}

// 关闭编辑模态框
function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
    document.getElementById('editForm').reset();
}

// 添加新链接
async function addNewLink() {
    const name = document.getElementById('linkName').value.trim();
    let url = document.getElementById('linkUrl').value.trim();

    if (!name || !url) {
        alert('请填写完整的链接信息');
        return;
    }
    
    // 自动添加http://前缀
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        url = 'http://' + url;
    }

    try {
        const response = await fetch(`/api/navigation/${currentCategory}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ name, url })
        });

        if (response.ok) {
            // 更新本地数据
            if (!allNavigationData[currentCategory]) {
                allNavigationData[currentCategory] = {};
            }
            allNavigationData[currentCategory][name] = url;
            
            // 更新链接顺序
            if (!linkOrder[currentCategory]) {
                linkOrder[currentCategory] = [];
            }
            linkOrder[currentCategory].push(name);
            
            // 保存到本地存储
            saveToLocalStorage();
            
            // 重新渲染分类
            renderCategory(currentCategory, allNavigationData[currentCategory]);
            
            closeModal();
            showSuccessMessage('链接添加成功！');
        } else {
            const error = await response.json();
            alert('添加失败: ' + error.error);
        }
    } catch (error) {
        console.error('添加链接失败:', error);
        alert('网络错误，请重试');
    }
}

// 更新链接
async function updateLink() {
    const newName = document.getElementById('editLinkName').value.trim();
    let newUrl = document.getElementById('editLinkUrl').value.trim();

    if (!newName || !newUrl) {
        alert('请填写完整的链接信息');
        return;
    }
    
    // 自动添加http://前缀
    if (!newUrl.startsWith('http://') && !newUrl.startsWith('https://')) {
        newUrl = 'http://' + newUrl;
    }

    try {
        const response = await fetch(`/api/navigation/${currentCategory}/${encodeURIComponent(currentEditName)}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ newName, url: newUrl })
        });

        if (response.ok) {
            // 更新本地数据
            delete allNavigationData[currentCategory][currentEditName];
            allNavigationData[currentCategory][newName] = newUrl;
            
            // 更新链接顺序
            if (linkOrder[currentCategory]) {
                const index = linkOrder[currentCategory].indexOf(currentEditName);
                if (index > -1) {
                    linkOrder[currentCategory][index] = newName;
                }
            }
            
            // 保存到本地存储
            saveToLocalStorage();
            
            // 重新渲染分类
            renderCategory(currentCategory, allNavigationData[currentCategory]);
            
            closeEditModal();
            showSuccessMessage('链接更新成功！');
        } else {
            const error = await response.json();
            alert('更新失败: ' + error.error);
        }
    } catch (error) {
        console.error('更新链接失败:', error);
        alert('网络错误，请重试');
    }
}

// 删除链接
async function deleteLink(category, name) {
    if (!confirm(`确定要删除链接 "${name}" 吗？`)) {
        return;
    }

    try {
        const response = await fetch(`/api/navigation/${category}/${encodeURIComponent(name)}`, {
            method: 'DELETE'
        });

        if (response.ok) {
            // 更新本地数据
            delete allNavigationData[category][name];
            
            // 更新链接顺序
            if (linkOrder[category]) {
                const index = linkOrder[category].indexOf(name);
                if (index > -1) {
                    linkOrder[category].splice(index, 1);
                }
            }
            
            // 保存到本地存储
            saveToLocalStorage();
            
            // 重新渲染分类
            renderCategory(category, allNavigationData[category]);
            
            showSuccessMessage('链接删除成功！');
        } else {
            const error = await response.json();
            alert('删除失败: ' + error.error);
        }
    } catch (error) {
        console.error('删除链接失败:', error);
        alert('网络错误，请重试');
    }
}

// 搜索过滤功能
function filterLinks(searchTerm) {
    if (!searchTerm.trim()) {
        // 如果搜索词为空，显示所有链接
        renderAllCategories();
        return;
    }

    const categories = ['my', 'ai', 'shopping', 'entertainment', 'news'];
    categories.forEach(category => {
        const links = allNavigationData[category] || {};
        const filteredLinks = {};
        
        Object.entries(links).forEach(([name, url]) => {
            if (name.toLowerCase().includes(searchTerm.toLowerCase()) || 
                url.toLowerCase().includes(searchTerm.toLowerCase())) {
                filteredLinks[name] = url;
            }
        });
        
        // 搜索时也保持排序
        renderCategory(category, filteredLinks);
    });
    
    // 如果当前tab没有搜索结果，显示提示
    const currentTabLinks = allNavigationData[currentTab] || {};
    const hasResults = Object.keys(currentTabLinks).some(name => 
        name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        currentTabLinks[name].toLowerCase().includes(searchTerm.toLowerCase())
    );
    
    if (!hasResults) {
        const container = document.getElementById(`${currentTab}-links`);
        if (container) {
            container.innerHTML = '<p style="color: #999; text-align: center; padding: 20px;">没有找到匹配的链接</p>';
        }
    }
}

// 显示成功消息
function showSuccessMessage(message) {
    // 创建临时消息提示
    const messageDiv = document.createElement('div');
    messageDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #28a745;
        color: white;
        padding: 15px 25px;
        border-radius: 8px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        z-index: 1001;
        animation: slideInRight 0.3s ease;
    `;
    messageDiv.textContent = message;
    
    document.body.appendChild(messageDiv);
    
    // 3秒后自动移除
    setTimeout(() => {
        messageDiv.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.parentNode.removeChild(messageDiv);
            }
        }, 300);
    }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);

// ==================== 收藏夹功能 ====================

// 显示收藏夹模态框
function showFavoritesModal() {
    document.getElementById('favoritesModal').style.display = 'block';
    renderFavorites();
    updateFolderSelects();
}

// 关闭收藏夹模态框
function closeFavoritesModal() {
    document.getElementById('favoritesModal').style.display = 'none';
}

// 显示新建文件夹模态框
function showAddFolderModal() {
    document.getElementById('addFolderModal').style.display = 'block';
    updateParentFolderSelect();
}

// 关闭新建文件夹模态框
function closeAddFolderModal() {
    document.getElementById('addFolderModal').style.display = 'none';
    document.getElementById('addFolderForm').reset();
}

// 显示添加收藏模态框
function showAddFavoriteModal() {
    document.getElementById('addFavoriteModal').style.display = 'block';
    updateFavoriteFolderSelect();
}

// 显示添加收藏模态框（指定文件夹）
function showAddFavoriteModalInFolder(folderId) {
    document.getElementById('addFavoriteModal').style.display = 'block';
    updateFavoriteFolderSelect();
    
    // 如果指定了文件夹，自动选中该文件夹
    if (folderId) {
        const folderSelect = document.getElementById('favoriteFolder');
        if (folderSelect) {
            folderSelect.value = folderId;
        }
    }
}

// 关闭添加收藏模态框
function closeAddFavoriteModal() {
    document.getElementById('addFavoriteModal').style.display = 'none';
    document.getElementById('addFavoriteForm').reset();
}

// 渲染收藏夹内容
function renderFavorites() {
    const container = document.getElementById('favoritesContent');
    
    if (favoritesData.folders.length === 0 && favoritesData.favorites.length === 0) {
        container.innerHTML = `
            <div class="empty-favorites">
                <i class="fas fa-heart"></i>
                <h4>收藏夹还是空的</h4>
                <p>开始创建文件夹和添加收藏吧！</p>
                <button class="add-folder-btn" onclick="showAddFolderModal()">
                    <i class="fas fa-folder-plus"></i> 创建第一个文件夹
                </button>
            </div>
        `;
        return;
    }
    
    let html = '';
    
    // 渲染根目录的收藏（没有文件夹的）
    const rootFavorites = favoritesData.favorites.filter(fav => !fav.folderId);
    if (rootFavorites.length > 0) {
        html += `
            <div class="favorite-folder">
                <div class="folder-header">
                    <div class="folder-info">
                        <i class="fas fa-star folder-icon"></i>
                        <span class="folder-name">根目录收藏</span>
                        <span class="folder-count">${rootFavorites.length}</span>
                    </div>
                    <div class="folder-actions">
                        <button class="folder-action-btn" onclick="toggleFolder('root')" title="展开/收起">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                    </div>
                </div>
                <div class="folder-content" id="root-folder">
                    ${rootFavorites.map(fav => renderFavoriteItem(fav)).join('')}
                </div>
            </div>
        `;
    }
    
    // 渲染文件夹
    favoritesData.folders.forEach(folder => {
        const folderFavorites = favoritesData.favorites.filter(fav => fav.folderId === folder.id);
        html += `
            <div class="favorite-folder">
                <div class="folder-header">
                    <div class="folder-info">
                        <i class="${folder.icon} folder-icon"></i>
                        <span class="folder-name">${folder.name}</span>
                        <span class="folder-count">${folderFavorites.length}</span>
                    </div>
                    <div class="folder-actions">
                        <button class="folder-action-btn" onclick="showAddFavoriteModalInFolder('${folder.id}')" title="在此文件夹添加收藏">
                            <i class="fas fa-plus"></i>
                        </button>
                        <button class="folder-action-btn" onclick="toggleFolder('${folder.id}')" title="展开/收起">
                            <i class="fas fa-chevron-down"></i>
                        </button>
                        <button class="folder-action-btn" onclick="editFolder('${folder.id}')" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="folder-action-btn" onclick="deleteFolder('${folder.id}')" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
                <div class="folder-content" id="${folder.id}-folder">
                    ${folderFavorites.map(fav => renderFavoriteItem(fav)).join('')}
                    ${folderFavorites.length === 0 ? `
                        <div class="empty-folder">
                            <p>此文件夹暂无收藏</p>
                            <button class="add-favorite-btn" onclick="showAddFavoriteModalInFolder('${folder.id}')">
                                <i class="fas fa-plus"></i> 添加第一个收藏
                            </button>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
}

// 渲染单个收藏项
function renderFavoriteItem(favorite) {
    return `
        <div class="favorite-item">
            <div class="favorite-info">
                <i class="fas fa-heart favorite-icon"></i>
                <div class="favorite-details">
                    <div class="favorite-name">${favorite.name}</div>
                    <div class="favorite-url">${favorite.url}</div>
                    ${favorite.description ? `<div class="favorite-description">${favorite.description}</div>` : ''}
                </div>
            </div>
            <div class="favorite-actions">
                <button class="favorite-action-btn" onclick="openFavorite('${favorite.url}')" title="打开">
                    <i class="fas fa-external-link-alt"></i>
                </button>
                <button class="favorite-action-btn" onclick="editFavorite('${favorite.id}')" title="编辑">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="favorite-action-btn delete" onclick="deleteFavorite('${favorite.id}')" title="删除">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `;
}

// 切换文件夹展开/收起状态
function toggleFolder(folderId) {
    const folderContent = document.getElementById(`${folderId}-folder`);
    const toggleBtn = folderContent.previousElementSibling.querySelector('.fa-chevron-down, .fa-chevron-up');
    
    if (folderContent.classList.contains('expanded')) {
        folderContent.classList.remove('expanded');
        toggleBtn.className = 'fas fa-chevron-down';
    } else {
        folderContent.classList.add('expanded');
        toggleBtn.className = 'fas fa-chevron-up';
    }
}

// 更新文件夹选择器
function updateFolderSelects() {
    updateParentFolderSelect();
    updateFavoriteFolderSelect();
}

// 更新父文件夹选择器
function updateParentFolderSelect() {
    const parentSelect = document.getElementById('parentFolder');
    if (!parentSelect) return;
    
    parentSelect.innerHTML = '<option value="">无（根目录）</option>';
    favoritesData.folders.forEach(folder => {
        const option = document.createElement('option');
        option.value = folder.id;
        option.textContent = folder.name;
        parentSelect.appendChild(option);
    });
}

// 更新收藏文件夹选择器
function updateFavoriteFolderSelect() {
    const folderSelect = document.getElementById('favoriteFolder');
    if (!folderSelect) return;
    
    folderSelect.innerHTML = '<option value="">根目录</option>';
    favoritesData.folders.forEach(folder => {
        const option = document.createElement('option');
        option.value = folder.id;
        option.textContent = folder.name;
        folderSelect.appendChild(option);
    });
}

// 添加新文件夹
function addNewFolder() {
    const name = document.getElementById('folderName').value.trim();
    const icon = document.getElementById('folderIcon').value;
    const parentId = document.getElementById('parentFolder').value;
    
    if (!name) {
        alert('请输入文件夹名称');
        return;
    }
    
    const newFolder = {
        id: 'folder_' + Date.now(),
        name: name,
        icon: icon,
        parentId: parentId || null,
        createdAt: new Date().toISOString()
    };
    
    favoritesData.folders.push(newFolder);
    saveToLocalStorage();
    closeAddFolderModal();
    renderFavorites();
    updateFolderSelects();
    showSuccessMessage('文件夹创建成功！');
}

// 添加新收藏
function addNewFavorite() {
    const name = document.getElementById('favoriteName').value.trim();
    const url = document.getElementById('favoriteUrl').value.trim();
    const folderId = document.getElementById('favoriteFolder').value;
    const description = document.getElementById('favoriteDescription').value.trim();
    
    if (!name || !url) {
        alert('请填写收藏名称和链接地址');
        return;
    }
    
    // 自动添加http前缀
    let finalUrl = url;
    if (!url.startsWith('http://') && !url.startsWith('https://')) {
        finalUrl = 'http://' + url;
    }
    
    const newFavorite = {
        id: 'favorite_' + Date.now(),
        name: name,
        url: finalUrl,
        folderId: folderId || null, // 如果folderId为空字符串，则设为null（根目录）
        description: description,
        createdAt: new Date().toISOString()
    };
    
    favoritesData.favorites.push(newFavorite);
    saveToLocalStorage();
    closeAddFavoriteModal();
    renderFavorites();
    showSuccessMessage('收藏添加成功！');
}

// 编辑文件夹
function editFolder(folderId) {
    const folder = favoritesData.folders.find(f => f.id === folderId);
    if (!folder) return;
    
    const newName = prompt('请输入新的文件夹名称:', folder.name);
    if (newName && newName.trim() && newName.trim() !== folder.name) {
        folder.name = newName.trim();
        saveToLocalStorage();
        renderFavorites();
        updateFolderSelects();
        showSuccessMessage('文件夹名称更新成功！');
    }
}

// 删除文件夹
function deleteFolder(folderId) {
    const folder = favoritesData.folders.find(f => f.id === folderId);
    if (!folder) return;
    
    const folderFavorites = favoritesData.favorites.filter(fav => fav.folderId === folderId);
    
    if (folderFavorites.length > 0) {
        if (!confirm(`文件夹"${folder.name}"中还有${folderFavorites.length}个收藏，删除文件夹将同时删除其中的所有收藏。确定要删除吗？`)) {
            return;
        }
        // 删除文件夹中的所有收藏
        favoritesData.favorites = favoritesData.favorites.filter(fav => fav.folderId !== folderId);
    }
    
    // 删除文件夹
    favoritesData.folders = favoritesData.folders.filter(f => f.id !== folderId);
    saveToLocalStorage();
    renderFavorites();
    updateFolderSelects();
    showSuccessMessage('文件夹删除成功！');
}

// 编辑收藏
function editFavorite(favoriteId) {
    const favorite = favoritesData.favorites.find(f => f.id === favoriteId);
    if (!favorite) return;
    
    const newName = prompt('请输入新的收藏名称:', favorite.name);
    if (newName && newName.trim() && newName.trim() !== favorite.name) {
        favorite.name = newName.trim();
        saveToLocalStorage();
        renderFavorites();
        showSuccessMessage('收藏名称更新成功！');
    }
}

// 删除收藏
function deleteFavorite(favoriteId) {
    if (!confirm('确定要删除这个收藏吗？')) {
        return;
    }
    
    favoritesData.favorites = favoritesData.favorites.filter(f => f.id !== favoriteId);
    saveToLocalStorage();
    renderFavorites();
    showSuccessMessage('收藏删除成功！');
}

// 打开收藏链接
function openFavorite(url) {
    window.open(url, '_blank');
}

// 搜索收藏夹
function searchFavorites(searchTerm) {
    if (!searchTerm.trim()) {
        renderFavorites();
        return;
    }
    
    const filteredFavorites = favoritesData.favorites.filter(fav => 
        fav.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
        fav.url.toLowerCase().includes(searchTerm.toLowerCase()) ||
        (fav.description && fav.description.toLowerCase().includes(searchTerm.toLowerCase()))
    );
    
    const container = document.getElementById('favoritesContent');
    
    if (filteredFavorites.length === 0) {
        container.innerHTML = `
            <div class="empty-favorites">
                <i class="fas fa-search"></i>
                <h4>没有找到匹配的收藏</h4>
                <p>尝试使用其他关键词搜索</p>
            </div>
        `;
        return;
    }
    
    let html = '<h4 style="margin-bottom: 15px; color: #495057;">搜索结果：</h4>';
    filteredFavorites.forEach(fav => {
        html += renderFavoriteItem(fav);
    });
    
    container.innerHTML = html;
}
